



alter       function f_carryplamt(
  @subjectid integer,
  @isdebit integer,
  @moneyid integer,
  @curryear integer,
  @currmonth integer,
  @filid  integer
)
returns @local_tab table(
  amt decimal(18,2),
  famt decimal(18,2) 
)
as  
begin                             
  declare @prioryear integer
  declare @priormonth integer
  declare @vouyearmonth varchar(6)
  declare @sstartamt decimal(18,2)
  declare @shappenamt decimal(18,2)
  declare @fstartamt decimal(18,2)
  declare @fhappenamt decimal(18,2)

  declare @bmbala decimal(18,2)
  declare @bysumdebit decimal(18,2)
  declare @bysumcredit decimal(18,2)
  declare @tmsumdebit decimal(18,2)
  declare @tmsumcredit decimal(18,2)
  declare @tmsum decimal(18,2)
  declare @fbmbala decimal(18,2)
  declare @fbysumdebit decimal(18,2)
  declare @fbysumcredit decimal(18,2)
  declare @ftmsumdebit decimal(18,2)
  declare @ftmsumcredit decimal(18,2)
  declare @ftmsum decimal(18,2)


  declare @nbalyear  integer
  declare @nbalmonth integer

  declare 
    @amt numeric(18,2),
    @famt numeric(18,2) 

  set @priormonth = @currmonth - 1
  if (@priormonth = 0) 
  begin
    set @priormonth = 12
    set @prioryear = @curryear - 1
  end else
    set @prioryear = @curryear

  set @vouyearmonth=cast(@curryear as char(4))+ right(cast(100+@currmonth as char(3)),2)

  if (@isdebit = 0) set @isdebit = -1
  select @nbalyear = nbalyear,
         @nbalmonth = nbalmonth,
         @bmbala = bmbala,
         @bysumcredit = bysumcredit,
         @bysumdebit = bysumdebit,
         @tmsumcredit = tmsumcredit,
         @tmsumdebit = tmsumdebit,
         @tmsum = tmsum,
         @fbmbala = fbmbala,
         @fbysumcredit = fbysumcredit,
         @fbysumdebit = fbysumdebit,
         @ftmsumcredit = ftmsumcredit,
         @ftmsumdebit = ftmsumdebit,
         @ftmsum =ftmsum
  from f_mssubgetpriorinfo(@moneyid,@subjectid, @prioryear,@priormonth,@filid)

  set @sstartamt=@isdebit *(@bmbala +  (@tmsumdebit - @tmsumcredit))
  set @fstartamt=@isdebit *(@fbmbala +  (@ftmsumdebit - @ftmsumcredit))

  if (@sstartamt is null)  set @sstartamt = 0
  if (@fstartamt is null)  set @fstartamt = 0
    
  select @shappenamt = @isdebit * (sum(d.dcdebitamt) - sum(d.dccreditamt)),
         @fhappenamt = @isdebit * (sum(d.debitamt) - sum(d.creditamt))
  from tfb_voucher m, tfb_voucherdtl d
  where m.voucherid = d.voucherid and m.vouyearmonth = @vouyearmonth 
  and (m.filid=@filid or @filid=-99) and d.moneyid=@moneyid
  and d.subjectid = @subjectid

  if (@shappenamt is null)  set @shappenamt = 0
  if (@fhappenamt is null)  set @fhappenamt = 0
  
  set @amt = round(@sstartamt + @shappenamt,2)
  set @famt = round(@fstartamt + @fhappenamt,2)

  insert into @local_tab(amt,famt)
  values(@amt,@famt)
  
  return
end








